#!/usr/bin/python

#Ganna Raboshchuk {ganna.raboshchuk@upc.edu}
#22.10.2013
#Updated: 24.11.2014. (the evaluation is performed by file; the length of hypothesis and reference is aligned)
#UPC, Barcelona

#Get the resultant scores with ACC metric.
#Only alarms are taken into account.
#--------------------------------------------------------------------------

import sys
import math

START_TIME = 0
END_TIME = 1
CLASS = 2

class_of_interest = 'al'

resultantLog = sys.argv[1]
resultFile = sys.argv[2]
labFile = sys.argv[3]
frameOverlap = float(sys.argv[4])

#Read the reference labelling for a specified file 
def getReference(filename, labFile): 
    reference = []
    labelling = open(labFile, 'r')
    readLabels = False
    for line in labelling:
        if (line == '"*/' + filename + '.lab"\n' ):
            readLabels = True
        if (line == '.\n') and readLabels:
            break
        if line[0].isdigit() and readLabels:            
            labels = line.split()
            timestamps = range(int(round((float(labels[END_TIME])-float(labels[START_TIME]))*math.pow(10,3)/frameOverlap)))
            for i in timestamps:
                reference.append(labels[CLASS])
    return reference        

#--------------------------------------------------------------------------
#MAIN code
filename = resultFile.split('/')[-1]
session = filename.split('_')[0]
overallResults = open(resultantLog, 'a')
overallResults.write(session + '\n')
      
results = open(resultFile, 'r')

hypothesis = []
reference = []
for line2 in results:
    line = line2
    if not line[0].isdigit():
        if (line != '#!MLF!#\n'):
            if (line != '.\n'): #filename string
                #Aligning the length of the hypothesis and reference (per file)
                length = min(len(reference), len(hypothesis))
                hypothesis = hypothesis[:length]
                reference = reference[:length]
                #Get reference
                tokens = line.split('/')
                filename = tokens[len(tokens)-1].split('.')[0]
                reference = reference + getReference(filename, labFile)                                     
    else:
        labels = line.split()
        hypothesis.append(labels[CLASS])

total_number = min(len(reference), len(hypothesis))
hypothesis = hypothesis[:total_number]
reference = reference[:total_number]

missed = 0
matched = 0
false_alarm = 0
total_frames = 0 #total number of referenced alarms frames
for i in range(len(hypothesis)):
    if reference[i] == class_of_interest:
        total_frames += 1
        missed += (reference[i] != hypothesis[i])
        matched += (reference[i] == hypothesis[i])
    if hypothesis[i] == class_of_interest and reference[i] != class_of_interest:
        false_alarm += 1
            
errors = false_alarm + missed

#Logging information
overallResults.write('\t FA: ' + str(false_alarm) + ', MS: ' + str(missed) + ', MA: ' + str(matched) + '\n')
overallResults.write('\t Total vo: ' +  str(total_frames) + ', Total frames: ' + str(total_number) + '\n')

if total_number == 0:
    overallResults.write('No reference samples found.\n')
else:
    acc = 1 - errors/float(total_number)                               
    overallResults.write('\t' + str(acc) + '\n')
                
                    
                

                    
            
    
